"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
import json

from .models import *
from siriuso.forms.widgets import LingvoInputWidget, LingvoTextWidget
from universo_bazo.models import Realeco
from siriuso.utils.admin_mixins import TekstoMixin


# Форма категорий уведомлений
class SciigoKategorioFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = SciigoKategorio
        fields = [field.name for field in SciigoKategorio._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Категории уведомлений
@admin.register(SciigoKategorio)
class SciigoKategorioAdmin(admin.ModelAdmin, TekstoMixin):
    form = SciigoKategorioFormo
    list_display = ('nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = SciigoKategorio


# Форма типов уведомлений
class SciigoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = SciigoTipo
        fields = [field.name for field in SciigoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы уведомлений
@admin.register(SciigoTipo)
class SciigoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = SciigoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = SciigoTipo


# Форма уведомлений
class SciigoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    kategorio = forms.ModelMultipleChoiceField(
        label=_('Категория уведомлений'),
        queryset=SciigoKategorio.objects.filter(forigo=False, publikigo=True)
    )
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = Sciigo
        fields = [field.name for field in Sciigo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Уведомления в
@admin.register(Sciigo)
class SciigoAdmin(admin.ModelAdmin, TekstoMixin):
    form = SciigoFormo
    list_display = ('nomo_teksto','priskribo_teksto','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    list_filter = ('sxablono_sistema',)

    class Meta:
        model = Sciigo
